var userTable;
var userAdminTable;
var pairTable;
var xmlhttp;
var userWithinTable;
var pairWithinTable;

function createUsersAdminTable(usersAdmin){
	var userAdminColumnDefs = [
	                       { key: "checkbox", label:"", formatter:"checkbox" },
	                       { key: "id", label: "Id", hidden:true },
	                       { key: "name", label: "Name"},
	                       { key: "email", label: "Email"}
	                     ];
	var emptyData = [""];
	var sampleData = [
	                  {id:"1", name:"name1", email:"email1"},
	                  {id:"2", name:"name2", email:"email2"},
	                 ];
	var userAdminDataSource = new YAHOO.util.DataSource(usersAdmin);
	userAdminTable = new YAHOO.widget.DataTable("userAdminTable", userAdminColumnDefs, userAdminDataSource);
	userAdminTable.subscribe("checkboxClickEvent", function (oArgs) {
		findSelectUnselectRows(oArgs, userAdminTable);
	});
	userAdminTable.subscribe("rowMouseoverEvent", userAdminTable.onEventHighlightRow);
	userAdminTable.subscribe("rowMouseoutEvent", userAdminTable.onEventUnhighlightRow);
	userAdminTable.subscribe("rowClickEvent", selectUnselectRowsUserAdminTable );
}

function createPairsTable(){
	var pairColumnDefs = [ 
	                       { key: "checkbox", label:"", formatter:"checkbox"},
		                   { key: "id1", label: "Id", hidden:true},
		                   { key: "id2", label: "Id", hidden:true},
		                   { key: "name", label: "Name", width:220, minWidth:220}		                
	                     ];
	var emptyData = [""];
	var pairDataSource = new YAHOO.util.DataSource(emptyData);
	pairTable = new YAHOO.widget.DataTable("pairTable", pairColumnDefs, pairDataSource);
	pairTable.subscribe("checkboxClickEvent", function (oArgs) {
		findSelectUnselectRows(oArgs, pairTable);
	});
	pairTable.subscribe("rowMouseoverEvent", userTable.onEventHighlightRow);
	pairTable.subscribe("rowMouseoutEvent", userTable.onEventUnhighlightRow);
	pairTable.subscribe("rowClickEvent", selectUnselectRowsPairTable );
}

function populateUsersTable(usersNotPaired){
	var userColumnDefs = [
	                      { key: "checkbox", label:"", formatter:"checkbox"},
	                      { key: "id", label: "Id", hidden:true},
	                      { key: "name", label: "Name", width:220, minWidth:220}	          
	                     ];
	var sampleData = [
	                      {id:"1", name:"fName1 lName1"},
	                      {id:"2", name:"fName2 lName2"},
	                      {id:"3", name:"fName3 lName3"},
	                      {id:"4", name:"fName4 lName4"},
	                      {id:"5", name:"fName5 lName5"},
	                      {id:"6", name:"fName6 lName6"},
	                      {id:"7", name:"fName7 lName7"},
	                      {id:"8", name:"fName8 lName8"},
	                      {id:"9", name:"fName9 lName9"},
	                      {id:"10", name:"fName10 lName10"}
	                     ];
	var userDataSource = new YAHOO.util.DataSource(usersNotPaired);
	userTable = new YAHOO.widget.DataTable("userTable", userColumnDefs, userDataSource);
	
	userTable.subscribe("checkboxClickEvent", function (oArgs) {
		findSelectUnselectRows(oArgs, userTable);
	});
	userTable.subscribe("rowMouseoverEvent", userTable.onEventHighlightRow);
	userTable.subscribe("rowMouseoutEvent", userTable.onEventUnhighlightRow);
    userTable.subscribe("rowClickEvent", selectUnselectRows );
}

function createPairsWithinTable(){
	var pairWithinColumnDefs = [ 
	                       { key: "checkbox", label:"", formatter:"checkbox"},
		                   { key: "sender", label: "Id", hidden:true},
		                   { key: "receiver1", label: "Id", hidden:true},
		                   { key: "receiver2", label: "Id", hidden:true},
		                   { key: "receiver3", label: "Id", hidden:true},
                           { key: "receiver4", label: "Id", hidden:true},
		                   { key: "name", label: "Name", width:220, minWidth:220}		                
	                     ];
	var emptyData = [""];
	var pairWithinDataSource = new YAHOO.util.DataSource(emptyData);
	pairWithinTable = new YAHOO.widget.DataTable("pairWithinTable", pairWithinColumnDefs, pairWithinDataSource);
	pairWithinTable.subscribe("checkboxClickEvent", function (oArgs) {
		findSelectUnselectRows(oArgs, pairWithinTable);
	});
	pairWithinTable.subscribe("rowMouseoverEvent", pairWithinTable.onEventHighlightRow);
	pairWithinTable.subscribe("rowMouseoutEvent", pairWithinTable.onEventUnhighlightRow);
    pairWithinTable.subscribe("rowClickEvent", selectUnselectRowsPairWithinTable );
}

function populateUsersWithinTable(usersNotPaired){
	var userWithinColumnDefs = [
	                      { key: "checkbox", label:"", formatter:"checkbox"},
	                      { key: "id", label: "Id", hidden:true},
	                      { key: "name", label: "Name", width:220, minWidth:220}	          
	                     ];
	var sampleData = [
	                      {id:"1", name:"fName1 lName1"},
	                      {id:"2", name:"fName2 lName2"},
	                      {id:"3", name:"fName3 lName3"},
	                      {id:"4", name:"fName4 lName4"},
	                      {id:"5", name:"fName5 lName5"},
	                      {id:"6", name:"fName6 lName6"},
	                      {id:"7", name:"fName7 lName7"},
	                      {id:"8", name:"fName8 lName8"},
	                      {id:"9", name:"fName9 lName9"},
	                      {id:"10", name:"fName10 lName10"}
	                     ];
	var userWithinDataSource = new YAHOO.util.DataSource(usersNotPaired);
	//userWithinDataSource = new YAHOO.util.DataSource(sampleDate);
	userWithinTable = new YAHOO.widget.DataTable("userWithinTable", userWithinColumnDefs, userWithinDataSource);
	
	userWithinTable.subscribe("checkboxClickEvent", function (oArgs) {
		findSelectUnselectRows(oArgs, userWithinTable);
	});
	userWithinTable.subscribe("rowMouseoverEvent", userWithinTable.onEventHighlightRow);
	userWithinTable.subscribe("rowMouseoutEvent", userWithinTable.onEventUnhighlightRow);
	userWithinTable.subscribe("rowClickEvent", selectUnselectRowsUserWithin );
}

function selectUnselectRows(oArgs) {
   var checkBox = oArgs.target.childNodes[0].childNodes[0].childNodes[0];
   checkBox.checked = !checkBox.checked;
   var row = userTable.getRecord(checkBox);
   row.setData("checkbox", checkBox.checked);
   if (checkBox.checked) {
       userTable.selectRow(row);
   } else {
	   userTable.unselectRow(row);
   }
}

function selectUnselectRowsPairTable(oArgs) {
   var checkBox = oArgs.target.childNodes[0].childNodes[0].childNodes[0];
   checkBox.checked = !checkBox.checked;
   var row = pairTable.getRecord(checkBox);
   row.setData("checkbox", checkBox.checked);
   if (checkBox.checked) {
	   pairTable.selectRow(row);
   } else {
	   pairTable.unselectRow(row);
   }
}

function selectUnselectRowsUserWithin(oArgs) {
   var checkBox = oArgs.target.childNodes[0].childNodes[0].childNodes[0];
   checkBox.checked = !checkBox.checked;
   var row = userWithinTable.getRecord(checkBox);
   row.setData("checkbox", checkBox.checked);
   if (checkBox.checked) {
	   userWithinTable.selectRow(row);
   } else {
	   userWithinTable.unselectRow(row);
   }
}

function selectUnselectRowsPairWithinTable(oArgs) {
   var checkBox = oArgs.target.childNodes[0].childNodes[0].childNodes[0];
   checkBox.checked = !checkBox.checked;
   var row = pairWithinTable.getRecord(checkBox);
   row.setData("checkbox", checkBox.checked);
   if (checkBox.checked) {
	   pairWithinTable.selectRow(row);
   } else {
	   pairWithinTable.unselectRow(row);
   }
}

function selectUnselectRowsUserAdminTable(oArgs) {
   var checkBox = oArgs.target.childNodes[0].childNodes[0].childNodes[0];
   checkBox.checked = !checkBox.checked;
   var row = userAdminTable.getRecord(checkBox);
   row.setData("checkbox", checkBox.checked);
   if (checkBox.checked) {
	   userAdminTable.selectRow(row);
   } else {
	   userAdminTable.unselectRow(row);
   }
}

function findSelectUnselectRows(oArgs, dataTable) {
	var elCheckbox = oArgs.target;
    var row = dataTable.getRecord(elCheckbox);
    elCheckbox.checked = ! elCheckbox.checked;
}

function removePair(){
	var i=0;
	var records = pairTable.getRecordSet().getRecords();
    if(records.length <=0 )
    	return;
    for(i=0; i< records.length; i++){
    	if((records[i].getData()).checkbox){
    		var userId1 = (records[i].getData()).id1;
    		var userId2 = (records[i].getData()).id2;
    		var name = ((records[i].getData()).name).split("<br/>");
    		var name1 = name[0];
    		var name2 = name[1];
    		var user = [{id:userId1, name:name1},{id:userId2, name:name2}];
    		userTable.addRows(user);
    		pairTable.deleteRow(i);
    		i=-1;
    	}	
    }
}

function addPair() {
	var user = new Array();
    var count = 0;
    var data = new Array();
    var i=0;
    var records = userTable.getRecordSet().getRecords();
    if(records.length <=0 )
    	return;
    for (i = 0; i < records.length; i++) {
    	if ((records[i].getData()).checkbox) {
    		var userID = (records[i].getData()).id;
        	var name = (records[i].getData()).name;
        	user[count++] = {id:userID, name:name};
        }
    }
    if(user.length != 2){
		alert("Select two users to be paired");
		count = 0;
		user = new Array();
		return;
	}
    addRow(user);
    for (i=0; i < records.length; i++) {
    	if ((records[i].getData()).checkbox) {
    		userTable.deleteRow(i);
    		i=-1;
    	}
    }
    YUIunselectAll();
}

function addWithinPair(){
	var withinAdding = document.getElementById("withinAdding").value;
	var user = new Array();
    var count = 0;
    var i=0;
    var records = userWithinTable.getRecordSet().getRecords();
    if(records.length <=0 )
    	return;
    for (i = 0; i < records.length; i++) {
    	if ((records[i].getData()).checkbox) {
    		var userID = (records[i].getData()).id;
        	var name = (records[i].getData()).name;
        	user[count++] = {id:userID, name:name};
        }
    }
    if(withinAdding == 'sender'){
    	if(user.length != 1){
	    	alert("Select 1 user as the sender");
	    	return;
	    }
	    addSender(user);
	    document.getElementById("withinAdding").value = 'receiver';
	    document.getElementById('senderAddWithin').style.display = 'none';
	    document.getElementById('receiverAddWithin').style.display = 'block';
    }else if(withinAdding == 'receiver'){
    	if(user.length !=4 ){
    		alert("Select 4 users as receivers");
    		return;
    	}
    	addReceivers(user);
    	document.getElementById("withinAdding").value = 'sender';
	    document.getElementById('senderAddWithin').style.display = 'block';
	    document.getElementById('receiverAddWithin').style.display = 'none';
    }
    
    for (i=0; i < records.length; i++) {
    	if ((records[i].getData()).checkbox) {
    		userWithinTable.deleteRow(i);
    		i=-1;
    	}
    }
    YUIunselectAllWithin();
}

function addSender(user){
	var name = "<strong>" + user[0]['name'] + " - Sender</strong><br/>";
	var data = {sender:user[0]['id'], name:name};
	pairWithinTable.addRow(data);
}

function addReceivers(user){
	var records = pairWithinTable.getRecordSet().getRecords();
	var length = records.length;
	var senderName = records[length-1].getData().name;
	var senderId = records[length-1].getData().sender;
	pairWithinTable.deleteRow(length-1);
    var radioString1 = "<input type='radio' value='"; 
    var radioString2 = "' name='anonymous"+ senderId +"'/>";
    var newName = senderName + radioString1 + user[0]['id'] + radioString2 + user[0]['name']  + "<br/>" + radioString1 + user[1]['id'] + radioString2 + user[1]['name']  + "<br/>" + radioString1 + user[2]['id'] + radioString2 + user[2]['name'] + "<br/>" + radioString1 + user[3]['id'] + radioString2 + user[3]['name']; 
	var data = {sender: senderId, receiver1: user[0]['id'], receiver2: user[1]['id'], receiver3: user[2]['id'], receiver4: user[3]['id'], name:newName};
    //alert(newName);
	pairWithinTable.addRow(data);
}

function removeWithinPair(){
    var i=0;
	var records = pairWithinTable.getRecordSet().getRecords();
    if(records.length <=0 )
    	return;
    for(i=0; i< records.length; i++){
    	if((records[i].getData()).checkbox){
            var sender = (records[i].getData()).sender;
            var receiver1 = (records[i].getData()).receiver1;
    		var receiver2 = (records[i].getData()).receiver2;
    		var receiver3 = (records[i].getData()).receiver3;
            var receiver4 = (records[i].getData()).receiver4;
    		var name = ((records[i].getData()).name).split("<br/>");
            var temp = name[0].split("-");
    		var senderName = temp[0];
    		var receiverName1 = (name[1].split("/>"))[1];
            var receiverName2 = (name[2].split("/>"))[1];
    		var receiverName3 = (name[3].split("/>"))[1];
            var receiverName4 = (name[4].split("/>"))[1];
            var user = [{id:sender, name:senderName},{id:receiver1, name:receiverName1},{id:receiver2, name:receiverName2},{id:receiver3, name:receiverName3},{id:receiver4, name:receiverName4}];
    		userWithinTable.addRows(user);
    		pairWithinTable.deleteRow(i);
    		i=-1;
    	}	
    }
}

function addRow(user){
	var name = user[0]['name'] + "<br/>" + user[1]['name'];
	var data = {id1:user[0]['id'], id2:user[1]['id'], name:name};
	pairTable.addRow(data);
}

function YUIselectAll() {
	records = userTable.getRecordSet().getRecords();
    for (i = 0; i < records.length; i++) {
        records[i].setData("checkbox", true);
        userTable.selectRow(records[i]);
    }
    userTable.render();
}

function YUIunselectAllWithin() {
    records = userWithinTable.getRecordSet().getRecords();
    for (i = 0; i < records.length; i++) {
    	records[i].setData("checkbox", false);
        userWithinTable.unselectRow(records[i]);
    }
    userWithinTable.render();
}

function YUIselectAllWithin() {
	records = userWithinTable.getRecordSet().getRecords();
    for (i = 0; i < records.length; i++) {
        records[i].setData("checkbox", true);
        userWithinTable.selectRow(records[i]);
    }
    userWithinTable.render();
}

function YUIunselectAll() {
    records = userTable.getRecordSet().getRecords();
    for (i = 0; i < records.length; i++) {
    	records[i].setData("checkbox", false);
        userTable.unselectRow(records[i]);
    }
    userTable.render();
}

function submitRandomForm(){
	document.getElementById('random').submit();
}

function submitSenderForm(){
	document.getElementById('SenderOnly').submit();
}

function submitExpiryForm(){
	var number = document.getElementById('maxSignUps').value;
	if(number != null || number != '' || parseInt(number) > 0)
		document.getElementById('expiryTime').submit();
}


function submitMaxSignUpForm(){
	var number = document.getElementById('maxSignUps').value;
	if(number != null || number != '' || parseInt(number) > 0)
		document.getElementById('maxSignUpsForm').submit();
}

function deleteSelected(){
	var i=0;
	var j=0;
	var usersArray = new Array();
	records = userAdminTable.getRecordSet().getRecords();
    if(records.length <=0 )
    	return;
    for(i=0; i< records.length; i++){
    	if((records[i].getData()).checkbox){
    		usersArray[j++] = (records[i].getData()).id;
    	}	
    }
    document.getElementById('userDeleteId').value = usersArray;
    document.getElementById('userDelete').submit();
}

function pairWithinSubmit(){
	document.getElementById('pairWithinError').style.display ='block';
	var pairs = pairWithinTable.getRecordSet();
	var length = pairs.getLength();
	if(length == 0){
		document.getElementById('pairWithinError').innerHTML = 'Please add atleast a pair !';
		document.getElementById('pairWithinError').className = "error";
		return;
	}		
	var senderWithin = new Array();
	var receiversWithin = new Array();
    var annonymousWithin = new Array();
	var test = new Array();
	for(i=0; i<length; i++){
		var record = pairs.getRecord(i);
		senderWithin[i] = record.getData("sender");
        var radioObj = document.getElementsByName("anonymous" + senderWithin[i]);
        var value = getCheckedValue(radioObj);
        if(value == "" || value == null){
            document.getElementById('pairWithinError').innerHTML = 'Select the anonymous receiver for all the pairs !';
            document.getElementById('pairWithinError').className = "error";
            return;
        }
        receiversWithin[i*3] = record.getData("receiver1");
		receiversWithin[i*3+1] = record.getData("receiver2");
		receiversWithin[i*3+2] = record.getData("receiver3");
        receiversWithin[i*3+3] = record.getData("receiver4");
        annonymousWithin[i] = value;
     }
	document.getElementById('senderWithin').value = senderWithin.toString();
	document.getElementById('receiversWithin').value = receiversWithin.toString();
    document.getElementById('annonymousWithin').value = annonymousWithin.toString();
	document.getElementById('pairsWithin').submit();
	//addPairs(userid1, userid2);
}

function formSubmit(){
	document.getElementById('pairError').style.display ='block';
	var pairs = pairTable.getRecordSet();
	var length = pairs.getLength();
	if(length == 0){
		document.getElementById('pairError').innerHTML = 'Please add atleast a pair !';
		document.getElementById('pairError').className = "error";
		return;
	}		
	var userid1 = new Array();
	var userid2 = new Array();
	var test = new Array();
	for(i=0; i<length; i++){
		var record = pairs.getRecord(i);
		userid1[i] = record.getData("id1");
		userid2[i] = record.getData("id2");
	}
	document.getElementById('userid1').value = userid1.toString();
	document.getElementById('userid2').value = userid2.toString();
	document.getElementById('pairs').submit();
	//addPairs(userid1, userid2);
}

function GetXmlHttpObject(){
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject){
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}

function addPairs(userid1, userid2){
	xmlhttp=GetXmlHttpObject();
	if (xmlhttp==null){
		alert ("Browser does not support HTTP Request");
		return;
	}
	var url = "addPair.php";
	url = url + "?userid1=" + userid1.toString() + "&userid2=" + userid2.toString();
	xmlhttp.onreadystatechange = stateChanged;
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);
}

function stateChanged(){
	if (xmlhttp.readyState==4){
		alert(xmlhttp.responseText);
	}
}

